//compress picture
import fs from 'fs'
import sharp from 'sharp'
import path from 'path'

/**
 * compress pictures
 * @param {String} filePath 
 * @param {Number} compressValue qulity.1-100 . more bigger more clarity
 * @param {String} outputFilePath 
 */
export const compress = async (filePath, compressValue, outputFilePath) => {
  outputFilePath = outputFilePath || filePath;//compress filePath if outputFilePath is undefined
  let extname = path.extname(outputFilePath)
  extname = extname.toLowerCase();
  let buf;
  switch (extname) {
    case '.png':
      let level = Math.ceil(10 - compressValue / 10);
      buf = await sharp(filePath).png({
        compressionLevel: level
      }).toBuffer();
      break;
    case '.jpg':
    case '.jpeg':
      buf = await sharp(filePath).jpeg({
        quality: compressValue
      }).toBuffer();
      break;
    case '.webp':
      buf = await sharp(filePath).webp({
        quality: compressValue
      }).toBuffer();
      break;
    case '.gif':
      buf = await sharp(filePath, { animated: true, limitInputPixels: false }).gif({
        colours: Math.max(2, Math.min(256, (Math.floor(compressValue / 100 * 256))))
      }).toBuffer();
    default:
      buf = await sharp(filePath).toBuffer();
  }
  fs.writeFileSync(outputFilePath, buf);
  return true;
}

export const resize = async (filePath, width, height, storeFilePath) => {
  storeFilePath = storeFilePath || filePath;
  let resizeOptions = { width, height, options: { fit: 'fill' } };
  let buf = await sharp(filePath).resize(resizeOptions).toBuffer();
  fs.writeFileSync(storeFilePath, buf);
  return true;
}